﻿using BCVP.Net8.Common;
using BCVP.Net8.Common.Caches;
using BCVP.Net8.Common.Core;
using BCVP.Net8.Common.Option;
using BCVP.Net8.IService;
using BCVP.Net8.Model;
using BCVP.Net8.Model.Vo;
using BCVP.Net8.Repository.UnitOfWorks;
using BCVP.Net8.Service;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using System.Data;

namespace BCVP.Net8.Controllers
{
    [ApiController]
    [Route("api/[controller]/[action]")]
    //[Authorize]
    //[Authorize(Roles = "SuperAdmin")]
    //[Authorize(Policy = "SystemOrAdmin")]
    //[Authorize(Policy = "Client")]    
    //[Authorize(Policy = "Permission")]
    [Authorize("Permission")]
    public class Test2Controller : ControllerBase
    {
        private readonly IBaseServices<Role, RoleVo> _roleService;
        private readonly IBaseServices<AuditSqlLog, AuditSqlLogVo> _auditSqlLogService;
        private readonly IUnitOfWorkManage _unitOfWorkManage;
        private readonly IUserService _userService;
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly IOptions<RedisOptions> _redisOptions;
        private readonly ICaching _caching;

        public IBaseServices<Role, RoleVo> _roleServiceObj { get; set; }
        public Test2Controller(
            IBaseServices<Role,RoleVo> roleService,
            IBaseServices<AuditSqlLog, AuditSqlLogVo> auditSqlLogService,
            IOptions<RedisOptions> redisOptions,
            ICaching caching,
            IUnitOfWorkManage unitOfWorkManage,
            IUserService userService,
            IHttpContextAccessor httpContextAccessor)
        {
            _roleService = roleService;
            _auditSqlLogService = auditSqlLogService;
            _redisOptions = redisOptions;
            _caching = caching;
            _unitOfWorkManage = unitOfWorkManage;
            _userService = userService;
            _httpContextAccessor = httpContextAccessor;
        }

        [HttpGet]
        public async Task<List<AuditSqlLogVo>> GetAuditSqlLog()
        {
            //var rltList = await _auditSqlLogService.QuerySplit(d => true);


            TimeSpan timeSpan = DateTime.Now.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
            var id = timeSpan.TotalSeconds.ObjToLong();
            await _auditSqlLogService.AddSplit(new AuditSqlLog()
            {
                Id = id,
                DateTime = Convert.ToDateTime("2023-12-23"),
            });

            //var rltList2 = await _auditSqlLogService.QuerySplit(d => d.DateTime <= Convert.ToDateTime("2023-12-24"));
            var rltList = await _auditSqlLogService.QuerySplit(d => true);

            return rltList;
        }
        [HttpGet]

        public async Task<object> GetClaims()
        {
            var httpContent = _httpContextAccessor.HttpContext?.User.Claims.ToList();
            foreach (var item in httpContent)
            {
                await Console.Out.WriteLineAsync($"{item.Type}:{item.Value}");
            }
            return new object();
        }

        [HttpGet]

        public async Task<List<RoleVo>> GetRoles2()
        {
            var roles = await _roleService.Query();
            var roless = await _userService.Query();
            return roles;
        }

        [HttpGet]
        public async Task<List<RoleVo>> GetRoles3()
        {
            var roles = await _roleServiceObj.Query();
            return roles;
        }

        [HttpGet]
        public async Task<List<RoleVo>> GetRoles4()
        {
            var roleServiceObjNew = App.GetService<IBaseServices<Role, RoleVo>>(false);
            var roleList = await roleServiceObjNew.Query();
            return roleList;
        }

        [HttpGet]
        public async Task<string> GetConfigurationRedis()
        {
            await Task.CompletedTask;
            var redisEnable = AppSettings.app(new string[] { "Redis", "Enable" });
            var redisConnectionString = AppSettings.GetValue("Redis:ConnectionString");
            return redisEnable + " " + redisConnectionString;
        }

        [HttpGet]
        public async Task<string> GetConfigurationRedis2()
        {
            await Task.CompletedTask;
            var redis = _redisOptions.Value;
            return JsonConvert.SerializeObject(redis);
        }

        [HttpGet]
        public async Task<string> GetConfigurationRedis3()
        {
            await Task.CompletedTask;
            var redisOptions = App.GetOptions<RedisOptions>();
            return JsonConvert.SerializeObject(redisOptions);
        }

        [HttpGet]
        public async Task<string> GetCache()
        {
            await Task.CompletedTask;
            var cachekey = "cache-key";
            await _caching.SetStringAsync(cachekey, "Hi Ruxingxing");
            return JsonConvert.SerializeObject(await _caching.GetAllCacheKeysAsync()) +
                JsonConvert.SerializeObject(await _caching.GetStringAsync(cachekey));
        }

        /// <summary>
        /// 测试事务
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<object> TestTransaction()
        {
            try
            {
                Console.WriteLine($"Begin Transaction");

                //_unitOfWorkManage.BeginTran();
                using var uow = _unitOfWorkManage.CreateUnitOfWork();
                var roles = await _roleService.Query();
                Console.WriteLine($"1 first time : the count of role is :{roles.Count}");


                Console.WriteLine($"insert a data into the table role now.");
                TimeSpan timeSpan = DateTime.Now.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
                var insertPassword = await _roleService.Add(new Role()
                {
                    Id = timeSpan.TotalSeconds.ObjToLong(),
                    IsDeleted = false,
                    Name = "role name",
                });

                var roles2 = await _roleService.Query();
                Console.WriteLine($"2 second time : the count of role is :{roles2.Count}");


                int ex = 0;
                Console.WriteLine($"There's an exception!!");
                Console.WriteLine($" ");
                int throwEx = 1 / ex;

                uow.Commit();
                //_unitOfWorkManage.CommitTran();
            }
            catch (Exception)
            {
                //_unitOfWorkManage.RollbackTran();
                var roles3 = await _roleService.Query();
                Console.WriteLine($"3 third time : the count of role is :{roles3.Count}");
            }

            return "ok";
        }

        [HttpGet]
        public async Task<object> TestTranPropagation()
        {
            return await _userService.TestTranPropagation();
        }
    }
}
